package com.woohua.demo.sercret;

import com.google.common.base.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.concurrent.NotThreadSafe;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;

/**
 * @author wooHua
 * @date 2022/6/27 9:45
 * @description
 */
@NotThreadSafe
public class HMacHelper {

    private static final Logger logger = LoggerFactory.getLogger(HMacHelper.class);
    private Mac mac;

    /**
     * MAC算法可选以下多种算法
     * HmacMD5/HmacSHA1/HmacSHA256/HmacSHA384/HmacSHA512
     */
    private static final String KEY_MAC = "HmacMD5";
    /**
     * 随机密钥
     */
    private static final String secretKey = "HYX77OdgODCYiksGylWKZvuNzfspMOOy";

    public HMacHelper(String key) {
        try {
            SecretKey secretKey = new SecretKeySpec(key.getBytes(Charsets.UTF_8), KEY_MAC);
            mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
        } catch (Exception e) {
            logger.error("create hmac helper failed.", e);
        }
    }

    public byte[] sign(byte[] content) {
        return mac.doFinal(content);
    }

    public boolean verify(byte[] signature, byte[] content) {
        try {
            byte[] result = mac.doFinal(content);
            return Arrays.equals(signature, result);
        } catch (Exception e) {
            logger.error("verify sig failed.", e);
        }
        return false;
    }

    public static void main(String[] args) {
        HMacHelper hMacHelper = new HMacHelper(secretKey);
        byte[] sign = hMacHelper.sign("哈哈哈哈".getBytes());
        System.out.println("hmac加密后的结果 ：" + sign.toString());
        boolean verify = hMacHelper.verify(sign, "哈哈哈哈".getBytes());

        System.out.println("校验结果 : " + verify);
    }
}
